import jwt
from django.conf import settings
from datetime import datetime, timedelta
from common.models import AuthUser
from django.contrib.auth.models import User

def generate_token(user_id):
    """生成JWT token"""
    payload = {
        'user_id': user_id,
        'exp': datetime.utcnow() + timedelta(days=7)  # token有效期7天
    }
    token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return token

def verify_token(token):
    """验证JWT token"""
    try:
        payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
        
        user_id = payload.get('user_id')
        if user_id:
            try:
                
                user = User.objects.get(id=user_id)
                return user.id
            except AuthUser.DoesNotExist:
                return None
        return None
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None 